About 1193 letters

About 6 minutes

#Python's thread creation

A thread is the smallest unit of execution that can be scheduled by the operating system. It represents an independent control flow within a process. A single process can contain multiple threads, which share the same memory and resources, but each has its own execution path.

In Python, you can create threads using the Thread class from the threading module:

t = Thread(target=entry_function, args=argument_list)

Example:

from threading import Thread, get_ident import time # Entry function for the thread def worker(name): for _ in range(3): print(f'{get_ident()}: My name is {name}') time.sleep(1) # Thread sleeps for 1 second t1 = Thread(target=worker, args=('worker1',)) # Create thread t2 = Thread(target=worker, args=('worker2',)) t1.start() # Start thread t2.start() t1.join() # Wait for thread to finish t2.join()

Output:

116776: My name is worker1 116616: My name is worker2 116776: My name is worker1 116616: My name is worker2 116776: My name is worker1 116616: My name is worker2

Created in 5/15/2025

Updated in 5/21/2025